<?php

/**
 * This class collect all the common function for models.
 */
class commonModel extends AppModel
{

    //获取全部
    public function getAll($where, $table, $orderby, $column_fields = '')
    {

        if (!empty($column_fields))
            $columns[0] = $column_fields;
        else
            $columns[0] = '*';

        $this->db->select($columns, $table);

        if (is_array($where)) {
            $tmp_where = $this->db->where($where);
        } else {
            $tmp_where = strlen($where) > 0 ? " Where  " . $where : "";
        }

        $this->db->putORLikeBoth('');
        $temp_orderby = "";
        if (is_array($orderby)) {
            $n = 1;
            $size = count($orderby);
            foreach ($orderby as $k => $v) {
                if ($n == $size) {
                    $temp_orderby .= ' ' . $k . " " . $v;
                } else {
                    $temp_orderby .= $k . " " . $v . ' , ';
                }
                $n++;
            }
            $this->db->orderBy($temp_orderby, '');
        }

//        echo $this->db->getStatement().'<br/>';//exit;
        $mysql_results = $this->db->execute();

        return $this->getArray($mysql_results);
    }

    public function getAllByPage($page, $number_page, $where, $table, $like, $orderby, $column_fields = '', $andlike = '')
    {
        if (is_null($page)) {
            $page = 1;
        }
        if (is_null($number_page)) {
            $number_page = 10;
        }
        $offset = ($page - 1) * $number_page;

        if (!empty($column_fields))
            $columns[0] = $column_fields;
        else
            $columns[0] = '*';

        $this->db->select($columns, $table);

        if (is_array($where)) {
            $tmp_where = $this->db->where($where);
        } else {
            $tmp_where = strlen($where) > 0 ? " Where  " . $where : "";
        }
        if ($andlike == "andlike") {
            $this->db->putAndLikeBoth($like);
        } else {
            $this->db->putORLikeBoth($like);
        }
        $this->db->limit($offset, $number_page);

        $temp_orderby = "";
        if (is_array($orderby)) {
            $n = 1;
            $size = count($orderby);
            foreach ($orderby as $k => $v) {
                if ($n == $size) {
                    $temp_orderby .= ' `' . $k . "` " . $v;
                } else {
                    $temp_orderby .= "`".$k . "` " . $v . ' , ';
                }
                $n++;
            }
            $this->db->orderBy($temp_orderby, '');
        }

//        echo $this->db->getStatement() . '<br/>'; //exit;
        $mysql_results = $this->db->execute();

        return $this->getArray($mysql_results);
    }

    public function getTotalCount($table, $where, $like, $andlike = "")
    {
        $tmp_where = '';
        $i = 0;
        if (is_array($where)) {
            $tmp_where = $this->db->where($where);
        } else {
            $tmp_where = strlen($where) > 0 ? " Where  " . $where : "";
        }

        $tmp_like = "";
        if (is_array($like)) {
            if ($andlike == "andlike") {
                $tmp_like = $this->db->putAndLikeBoth($like);
            } else {
                $tmp_like = $this->db->putORLikeBoth($like);
            }
        } else {
            $tmp_like = strlen($like) > 0 ? " " . $like : "";
        }

        $tmp_where .= strlen($tmp_where) > 0 ? (strlen($tmp_like) > 0 ? " AND  (" . $tmp_like . ")" : "") : (strlen($tmp_like) > 0 ? " WHERE " . $tmp_like : "");

        $sql = 'select count(*) as count from ' . $table . $tmp_where;
        //echo $sql;
        $this->db->putORLikeBoth('');
        $this->db->setStatement($sql);

        $stmt = $this->db->getStatement();
//        echo '$stmt= '.$stmt."<br/>";
        //exit;
        $mysql_results = $this->db->execute();
        $total_num = 0;
        $total_result = mysqli_fetch_array($mysql_results, MYSQLI_ASSOC);
        if (!empty($total_result) && count($total_result) > 0) {
            $total_num = $total_result["count"];
        }

        return $total_num;
    }

    public function getJoinByPage($page, $number_page, $where, $table, $joinTables, $joinOn, $like, $orderby, $column_fields = '')
    {
        if (is_null($page)) {
            $page = 1;
        }
        if (is_null($number_page)) {
            $number_page = 10;
        }
        $offset = ($page - 1) * $number_page;

        if (!empty($column_fields))
            $columns[0] = $column_fields;
        else
            $columns[0] = '*';

        $this->db->select($columns, $table);
        $this->db->innerJoin($joinTables);
        $this->db->joinOn($joinOn);
        if (is_array($where)) {
            $tmp_where = $this->db->where($where);
        } else {
            $tmp_where = strlen($where) > 0 ? " Where  " . $where : "";
        }

        $this->db->putORLikeBoth($like);
        $this->db->limit($offset, $number_page);

        $temp_orderby = "";
        if (is_array($orderby)) {
            $n = 1;
            $size = count($orderby);
            foreach ($orderby as $k => $v) {
                if ($n == $size) {
                    $temp_orderby .= ' ' . $k . " " . $v;
                } else {
                    $temp_orderby .= $k . " " . $v . ' , ';
                }
                $n++;
            }
            $this->db->orderBy($temp_orderby, '');
        }

//        echo $this->db->getStatement() . '<br/>'; //exit;
        $mysql_results = $this->db->execute();

        return $this->getArray($mysql_results);
    }

    public function getItemById($id, $table)
    {
        $columns[0] = '*';
        $where = array("" => array("=" => array('id' => $id)));

        $this->db->select($columns, $table);
        $this->db->where($where);
        $this->db->putORLikeBoth('');
        $mysql_results = $this->db->execute();
        //echo $this->db->getStatement().'<br/>';
        return $this->getArray($mysql_results, 'one');
    }

    public function deleteItem($where, $table)
    {
        try {
            $this->db->delete($table);
            $this->db->where($where);
            $mysql_results = $this->db->execute();
            return true;
        } catch (Exception $e) {
            return false;
        }
    }

    public function getItemByOther($where, $table)
    {
        $columns[0] = '*';
        $this->db->select($columns, $table);
        $this->db->where($where);
        //$this->db->orderBy('id', "desc");
        $this->db->putORLikeBoth('');
        $stmt = $this->db->getStatement();
        // echo $stmt;
        $mysql_results = $this->db->execute();
        return $this->getArray($mysql_results);
    }

    public function addItem($columns, $table)
    {
        $this->db->insert($columns, $table);
		 $stmt = $this->db->getStatement();
//        echo $stmt;
//        exit;
        $new_id = $this->db->execute();
 
        return $new_id;
    }

    public function updateItem($columns, $where, $table)
    {
        $this->db->update($columns, $table);
        $this->db->where($where);
        $this->db->putORLikeBoth('');
//        echo $this->db->getStatement();
//        exit;
        $mysql_results = $this->db->execute();
        return $mysql_results;
    }

    public function getItemByCol($where, $table, $orderby = '')
    {
        $columns[0] = '*';
        $this->db->select($columns, $table);
        $this->db->where($where);
        $this->db->putORLikeBoth('');
        if (strlen($orderby) > 0)
            $this->db->orderBy($orderby, "desc");
        $stmt = $this->db->getStatement();
        //echo $stmt;
        $mysql_results = $this->db->execute();
        return $this->getArray($mysql_results, 'one');
    }

    public function updateItemStatus($id, $table)
    {
        $sql = 'update ' . $table . ' SET status=(case status when 1 then 0 else 1 end) WHERE id=' . $id;

        $this->db->setStatement($sql);
        //echo $this->db->getStatement().'<br/>';
        $mysql_results = $this->db->execute();
        return $mysql_results;
    }

    public function addCountByColName($where_col, $where_value, $col, $table)
    {
        $sql = 'update ' . $table . ' SET ' . $col . '=' . $col . '+1  WHERE `' . $where_col . '`=' . $where_value;
        $this->db->setStatement($sql);
        $mysql_results = $this->db->execute();
        return $mysql_results;
    }

    public function reduceCountByColName($where_col, $where_value, $col, $table)
    {
        $sql = 'update ' . $table . ' SET ' . $col . '=' . $col . '-1  WHERE `' . $where_col . '`=' . $where_value;
        $this->db->setStatement($sql);
        $mysql_results = $this->db->execute();
        return $mysql_results;
    }

    public function getArray($mysql_results, $info = "")
    {
        $data = array();
        if (!empty($mysql_results) && count($mysql_results) > 0) {
            while ($row = mysqli_fetch_array($mysql_results, MYSQLI_ASSOC)) {
                if ($info == "one") {
                    $data = $row;
                } else {
                    $data[] = $row;
                }
            }
        }

        return $data;
    }

    public function setLog($field, $original, $modify)
    {
        $table = "logdata";
        $_org = array();
        $_modi = array();
        unset($modify["updatedt"]);
        foreach ($modify as $key => $value) {
            if (empty($original)) {   // add $orginal is empty
                $_modi = $modify;
            } else if (array_key_exists($key, $original) && $value != $original[$key]) {
                $_org[$key] = $original[$key];
                $_modi[$key] = $modify[$key];
            }
        }
        $field['createdt'] = 'now()';
        $field['editor_id'] = $_SESSION['zp_manage']['uid'];
        $_org = Tools::transcoding($_org);
        $field['original'] = urldecode(json_encode($_org));
        $_modi = Tools::transcoding($_modi);
        $field['modify'] = urldecode(json_encode($_modi));
        $this->addItem($field, $table);
    }

    public function setLog_SHOP($field, $original, $modify)
    {
        $table = "logdata";
        $_org = array();
        $_modi = array();
        unset($modify["updatedt"]);
        foreach ($modify as $key => $value) {
            if (empty($original)) {   // add $orginal is empty
                $_modi = $modify;
            } else if (array_key_exists($key, $original) && $value != $original[$key]) {
                $_org[$key] = $original[$key];
                $_modi[$key] = $modify[$key];
            }
        }
        $field['createdt'] = 'now()';
        $field['editor_id'] = $_SESSION['zp_shop']['store_id'];
        $_org = Tools::transcoding($_org);
        $field['original'] = urldecode(json_encode($_org));
        $_modi = Tools::transcoding($_modi);
        $field['modify'] = urldecode(json_encode($_modi));
        $this->addItem($field, $table);
    }

    public function CompaySetLog($field, $original, $modify)
    {
        $table = "logdata";
        $_org = array();
        $_modi = array();
        unset($modify["updatedt"]);
        foreach ($modify as $key => $value) {
            if (empty($original)) {   // add $orginal is empty
                $_modi = $modify;
            } else if (array_key_exists($key, $original) && $value != $original[$key]) {
                $_org[$key] = $original[$key];
                $_modi[$key] = $modify[$key];
            }
        }
        $field['createdt'] = 'now()';
        $field['editor_id'] = $_SESSION['zp_company']['company_code'];
        $_org = Tools::transcoding($_org);
        $field['original'] = urldecode(json_encode($_org));
        $_modi = Tools::transcoding($_modi);
        $field['modify'] = urldecode(json_encode($_modi));
        $this->addItem($field, $table);
    }


    /*
     *  新增指派记录
     * $express_order: 数组
     * $active：int
     */
    public function addExpressData($express_order, $active){

        $add_express_data=array();
        $add_express_data['order_no'] = $express_order['order_no'];
        $add_express_data['shop_express_no'] = $express_order['shop_express_no'];
        $add_express_data['express_no'] =isset($express_order['express_order_no'])? $express_order['express_order_no']:'';
        $add_express_data['express_type'] = $express_order['express_type'];
        $add_express_data['shop_code'] = $active;
        $add_express_data['shop_code_desc'] = Data::$_express_status[$active];
        $add_express_data['createdt'] = 'now()';
//        $add_express_data['create_id'] = $_SESSION['zp_shop']['store_id'];
        $data_id=$this->addItem($add_express_data, 'express_data');

        return $data_id;
    }

    /*
     *  更新指派记录
     * $data_id: int 指派_id
     * $info：数组  接口回传的资料
     */
    public function updateExpressData($data_id, $info){
        $express_result=$info['result_code'] == 0?'OK':'FAIL';
        $field=array();
        $field['express_code'] = $info['express_code'];
        $field['express_code_desc'] =$info['express_code_desc'];
        $field['express_data'] = json_encode($info,JSON_UNESCAPED_UNICODE);
        $field['express_result'] = $express_result;

        $where_fields = array("AND" => array("=" => array('id' => $data_id)));
        $r_o = $this->updateItem($field, $where_fields, 'express_data');

    }



    public function getTotalCountByJoin($sql) {
        $sql = "select count(*) count from (" . $sql . ") a";
        $this->db->setStatement($sql);
        $mysql_results = $this->db->execute();
        $total_num = 0;
        $total_result = mysqli_fetch_array($mysql_results);
        if (!empty($total_result) && count($total_result) > 0) {
            $total_num = $total_result["count"];
        }
        return $total_num;
    }


    public function getTotalCountByJoinID($sql) {
        $sql = "select count(id) count from (" . $sql . ") a";
        $this->db->setStatement($sql);
        $mysql_results = $this->db->execute();
        $total_num = 0;
        $total_result = mysqli_fetch_array($mysql_results);
        if (!empty($total_result) && count($total_result) > 0) {
            $total_num = $total_result["count"];
        }
        return $total_num;
    }

    public function getJoinByPageR($page, $number_page, $sql) {

        if (is_null($page))
            $page = 1;
        if (is_null($number_page))
            $number_page = current(Data::$_number_pages);
        $offset = ($page - 1) * $number_page;
        $limit = ' LIMIT  ' . $offset . ', ' . $number_page . ' ';
        $sql .= $limit;
//		echo $sql;
        $this->db->setStatement($sql);
        $mysql_results = $this->db->execute();
        return $mysql_results;
    }

    public function getJoinAllByPage($page, $number_page, $where, $table, $like, $orderby) {
        if (is_null($page)) {
            $page = 1;
        }
        if (is_null($number_page)) {
            $number_page = 10;
        }
        $offset = ($page - 1) * $number_page;

        $columns[0] = '*';

        $this->db->select($columns, $table);
        $this->db->where($where);
        $this->db->putAndLikeBoth($like);
        $this->db->limit($offset, $number_page);
        if (strlen($orderby) > 0) {
            $desc = $orderby == "rank" ? "asc" : "desc";
            $this->db->orderBy($orderby, $desc);
        }
        //echo $this->db->getStatement().'<br/>';
        $mysql_results = $this->db->execute();

        return $mysql_results;
    }

    public function getAny($sql) {
        $this->db->setStatement($sql);
        $mysql_results = $this->db->execute();
        return $mysql_results;
    }


    public function elmexecute($field)
    {

        $result = $this->db->elmexecute($field);

        return $result;
    }

}

?>
